import axios from 'axios'
import store from '@/store'
import { getToken } from '@/util/auth'
import {
  Toast
} from 'vant'
import router from '@/router/index'
const ERR_OK = 200
const ERR_ERR = 401
const ERR_NOR = 422
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})
let loadingToast
service.interceptors.request.use(
  config => {
    loadingToast = Toast({
      type: 'loading',
      duration: 0,
      message: '加载中...',
      forbidClick: false
    })
    if (store.getters.token) {
      config.headers.Authorization = 'Bearer ' + store.getters.token
    } else {
      config.headers.Authorization = 'Bearer ' + getToken()
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    Toast.clear()
    if (res.code === ERR_OK) {
      return Promise.resolve(res)
    }
  },
  error => {
    loadingToast.clear()
    // console.log(error.response) // for debug
    if (error.response.status === ERR_ERR && window.location.hash !== '#/my') {
      if (router.currentRoute.fullPath.includes('/home?couponId')) {
        router.replace({ path: '/login', query: { redirect_url: router.currentRoute.fullPath } })
      } else {
        router.replace({ path: '/login' })
      }
      // router.replace({ path: '/login', query: router.currentRoute.query.redirect_url })
      Toast('暂未登录~')
    }
    if (error.response.status === ERR_NOR) {
      Toast({
        type: 'fail',
        message: error.response.data.message,
        duration: 3000
      })
      console.log(error.response.data.message)
    }
    // if (error.response.status === ERR_ERR) {
    //   // router.go(-1)
    // }
    return Promise.reject(error.response)
  }
)

export default service
